//创建用户相关的小仓库
import { defineStore } from 'pinia'
//引入登录接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from '@/api/user/type'
import type { UserState } from './type/type'
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
//引入常量路由
import { constantRoute, asnycRoute, anyRoute } from '@/router/routers'
//引入深拷贝方法
//@ts-ignore
import { cloneDeep } from 'lodash/cloneDeep'
import router from '@/router'

//用于过滤当前用户想要展示的异步路由
function filterAsyncRoute(asnycRoute: any, routes: any) {
  return asnycRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}

//创建小仓库
let useUserStore = defineStore('User', {
  state: (): UserState => {
    //存储数据的地方
    return {
      token: GET_TOKEN(), //存储用户唯一标识
      menuRoutes: constantRoute, //仓库存储生成菜单需要数组
      username: '',
      avatar: '',
      buttons:[]
    }
  },
  actions: {
    //用户登录方法
    async userLogin(data: loginFormData) {
      //登录请求
      let result: loginResponseData = await reqLogin(data)
      console.log(result)
      //成功=>200
      //失败=>201
      if (result.code == 200) {
        this.token = result.data as string
        //本地存储持久化
        SET_TOKEN(result.data as string)
        //能保证当前async函数返回一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    //用户获取信息方法
    async userInfo() {
      //获取用户信息进行存储仓库当中
      let result: userInfoResponseData = await reqUserInfo()
      console.log(result.data.routes)
      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        this.buttons=result.data.buttons
        //计算当前用户需要展示的异步路由
        let userAsyncRoute = filterAsyncRoute(asnycRoute, result.data.routes)
        //菜单的数据
        this.menuRoutes=[...constantRoute,...userAsyncRoute,anyRoute];
        //目前路由器管理只有常量路由：追加异步路由和任意路由动态
        [...userAsyncRoute,anyRoute].forEach((route:any)=>{
            router.addRoute(route);
        })
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    //退出登录
    async userLogout() {
      let result: any = await reqLogout()
      if (result.code == 200) {
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
}) //state 是 store 的数据 (data)，getters 是 store 的计算属性 (computed)，
// 而 actions 则是方法 (methods)

//对外暴露
export default useUserStore
